package com.kamistoat.meimeimall.meimeimallproduct.scheduled;

import com.kamistoat.meimeimall.common.runTimeFunc.RunTimeLog;
import com.kamistoat.meimeimall.meimeimallproduct.dao.SpuInfoDao;
import com.kamistoat.meimeimall.meimeimallproduct.service.SpuInfoService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AsyncProductToES {
    @Autowired
    SpuInfoService spuInfoService;
    @Autowired
    SpuInfoDao spuInfoDao;
    @Autowired
    RedissonClient redissonClient;

    // 写入操作都需要分布式锁
    private final String async_lock = "product:async_to_ES:lock";

    @Scheduled(cron = "0 0/30 * * * ?")
    // @Scheduled(cron = "30 * * * * ?")
    public void asyncProductToES() {
        RLock asyncLock = redissonClient.getLock(async_lock);
        // 锁最长持有3分钟
        asyncLock.lock(3, TimeUnit.MINUTES);
        try {
            RunTimeLog.printRunTimeLog("开始进行ES商品信息同步");
            List<Long> spuIdList = spuInfoDao.getAllSpuId();
            for (Long spuId : spuIdList) {
                spuInfoService.spuUp(spuId);
            }
            RunTimeLog.printRunTimeLog("ES商品信息同步完成");
        } catch (Exception e) {
            RunTimeLog.printRunTimeLog("ES信息同步时发生异常:" + e.getMessage());
        } finally {
            asyncLock.unlock();
        }
    }

}
